package log

import (
	"github.com/spf13/viper"
	"io"
	"os"
	"path/filepath"
	"sync"
	"time"
)

const kb int64 = 1024
const mb int64 = 1024 * 1024
const fileSize = 50 * mb //文件最大大小
const LOG_TYPE_FILE = "file"
const LOG_TYPE_KAFKA = "kafka"
const default_logtype = LOG_TYPE_FILE

var (
	logchan  chan string
	logfile  *os.File
	filelock sync.Mutex
	dirpath  string //文件夹路径
	logtype  string
)

func InitLogs() {
	types := viper.GetString("log.types")
	switch types {
	case LOG_TYPE_FILE:
		logtype = LOG_TYPE_FILE
		initDirPath() //初始化文件夹路径
		initlogfile() //初始化日志文件
		go daychangefile()
	case LOG_TYPE_KAFKA:
		logtype = LOG_TYPE_KAFKA
	default:
		logtype = default_logtype
		initDirPath() //初始化文件夹路径
		initlogfile() //初始化日志文件
		go daychangefile()
	}
	logchan = make(chan string, 100)
	go start()
}

//初始化文件夹路径，并创建文件夹
func initDirPath() {
	//初始化文件路径
	nowstr := time.Now().Format("2006-01-02")
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
		return
	}
	dirpath = filepath.Join(dir, "config/Log", nowstr) //文件夹路径
	//创建文件夹
	err = os.MkdirAll(dirpath, os.ModePerm)
	if err != nil {
		panic(err)
		return
	}
}

func WriteLog(str string) {
	logchan <- str
}
func start() {
	for {
		str := <-logchan
		//fmt.Println(str)
		switch logtype {
		case LOG_TYPE_FILE:
			checkFileSize()
			filelock.Lock()
			io.WriteString(logfile, str)
			filelock.Unlock()
		case LOG_TYPE_KAFKA:

		default:
		}
	}
}

//检验文件的大小
func checkFileSize() {
	fInfo, _ := logfile.Stat()
	if fInfo.Size() >= fileSize {
		initlogfile()
	}
}
func pathexist(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
func daychangefile() {
	now := time.Now()
	next := now.Add(time.Hour * 24)
	for {
		next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
		select {
		case <-time.After(next.Sub(now)):
			initDirPath()
			initlogfile()
		}
	}
}
func initlogfile() {
	//创建文件夹
	nowstr := time.Now().Format("2006-01-02-150405.000")
	fp := filepath.Join(dirpath, nowstr+".log") //日志文件路径
	has, err := pathexist(fp)
	if err != nil {
		panic(err)
	}
	filelock.Lock()
	if has {
		logfile, err = os.OpenFile(fp, os.O_WRONLY|os.O_APPEND, 0666)
	} else {
		_, err = os.Create(fp)
		logfile, _ = os.OpenFile(fp, os.O_WRONLY, 0644)
	}
	filelock.Unlock()
}
